package com.baozun.houji.goods.fragment

import android.os.Bundle
import android.view.View
import androidx.core.content.ContextCompat
import androidx.viewpager2.widget.ViewPager2
import com.alibaba.android.arouter.launcher.ARouter
import com.azhon.appupdate.manager.DownloadManager
import com.baozhun.mall.common.BuildConfig
import com.baozhun.mall.common.activity.WebContainerActivity
import com.baozhun.mall.common.arouter.RoutePath
import com.baozhun.mall.common.base.BaseFragment
import com.baozhun.mall.common.ext.showToast
import com.baozhun.mall.common.model.enums.ApiEnvironment
import com.baozhun.mall.common.model.enums.AppUpdateType
import com.baozhun.mall.common.util.CacheUtil
import com.baozhun.mall.common.util.Constants
import com.baozhun.mall.common.util.eventbus.EventBusUtils
import com.baozhun.mall.common.util.eventbus.EventCode
import com.baozhun.mall.common.util.eventbus.EventMessage
import com.baozhun.mall.common.widget.dialog.CommonDialog
import com.baozun.houji.goods.R
import com.baozun.houji.goods.activity.SearchActivity
import com.baozun.houji.goods.adapter.CategoryPageListAdapter
import com.baozun.houji.goods.databinding.FragmentHomeBinding
import com.baozhun.mall.common.model.HomePageBean
import com.baozhun.mall.common.model.bean.ClassifyInfo
import com.baozhun.mall.common.model.enums.GoodsType
import com.baozhun.mall.common.util.AppUtil
import com.baozun.houji.goods.adapter.HomeTopCategoryViewPagerAdapter
import com.baozun.houji.goods.model.bean.HomeGoldenBean
import com.baozun.houji.goods.viewmodel.state.HomeViewModel
import com.blankj.utilcode.util.SPUtils
import com.donkingliang.consecutivescroller.ConsecutiveScrollerLayout
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayout.GONE
import com.google.android.material.tabs.TabLayout.OnTabSelectedListener
import com.google.android.material.tabs.TabLayout.VISIBLE
import com.google.android.material.tabs.TabLayoutMediator
import com.hjq.bar.OnTitleBarListener
import com.lxj.xpopup.XPopup
import com.orhanobut.logger.Logger
import com.scwang.smart.refresh.layout.api.RefreshFooter
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener
import com.scwang.smart.refresh.layout.listener.OnRefreshListener
import com.scwang.smart.refresh.layout.simple.SimpleMultiListener
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


/**
 * @Title：首页fragment
 * @Description：
 * @Author：xuefeng.zhu
 * @Since：2022/11/4
 * @Version：1.0.0
 */
class HomeFragment : BaseFragment<HomeViewModel, FragmentHomeBinding>(), OnTitleBarListener, OnRefreshListener, OnLoadMoreListener,
    ConsecutiveScrollerLayout.OnStickyChangeListener, ConsecutiveScrollerLayout.OnScrollChangeListener, OnTabSelectedListener,
    View.OnLongClickListener {
    private val HOME_DATA_REFRESH_LIMIT: Long = 30 * 60 * 1000L
    private var mLeaveTime = 0L
    var mFragmentList = mutableListOf<CategoryFragment>()
    private var mCategoryPageListAdapter: CategoryPageListAdapter? = null
    private var mCategoryViewPageSize = 1
    private var mIsInit: Boolean = true


    override fun initView(savedInstanceState: Bundle?) {
        EventBusUtils.register(this)
        mDataBinding.ivHouji.setOnLongClickListener(this)
        mDataBinding.homeRefreshRv.setOnRefreshListener(this)
        mDataBinding.homeRefreshRv.setOnLoadMoreListener(this)
        mDataBinding.scrollerLayout.onVerticalScrollChangeListener = this

        mDataBinding.homeRefreshRv.setOnMultiListener(object : SimpleMultiListener() {
            override fun onFooterMoving(
                footer: RefreshFooter,
                isDragging: Boolean,
                percent: Float,
                offset: Int,
                footerHeight: Int,
                maxDragHeight: Int
            ) {
                // 上拉加载时，保证吸顶头部不被推出屏幕。
                mDataBinding.scrollerLayout.stickyOffset = offset
            }
        })
        mDataBinding.scrollerLayout.onStickyChangeListener = this
    }


    override fun initData() {
        super.initData()
        mViewModel.getAppUpdateInfo()
    }

    override fun onPause() {
        super.onPause()
        mLeaveTime = System.currentTimeMillis()
    }

    override fun onResume() {
        super.onResume()
        mViewModel.requestUserInfo()
        mDataBinding.llMainLayout.setBackgroundColor(ContextCompat.getColor(mActivity, com.baozhun.mall.res.R.color.white))
        //重新唤醒后每30分钟刷新一次首页数据
        if (mLeaveTime > 0L && System.currentTimeMillis() - mLeaveTime >= HOME_DATA_REFRESH_LIMIT) {
            Logger.e("onResume=>lazyLoadData")
            mLeaveTime = System.currentTimeMillis()
            lazyLoadData()
        }
    }


    /**
     * 懒加载
     */
    override fun lazyLoadData() {
        mIsInit = true
        mDataBinding.homeRefreshRv.finishRefresh()
        mViewModel.getHomeGoldenData()
        mViewModel.getHomeData()
    }

    override fun createObserver() {
        mViewModel.mHomeData.observe(this) {
            mDataBinding.homeRefreshRv.finishRefresh()
            CacheUtil.setAppConfig(CacheUtil.getAppConfig().apply { advertisement_url = it.advertisement_url })
            initCategoryNavData(it)
        }
        mViewModel.homeGoldenBean.observe(this) {
            initTopCategoryClass(it)
        }
        mViewModel.appUpdateBean.observe(this) {
            if (it.is_force != AppUpdateType.NO_UPDATE.type) {
                XPopup.Builder(mActivity).dismissOnTouchOutside(false).dismissOnBackPressed(false)
                    .asCustom(CommonDialog(mActivity, onConfirmListener = {
                        val manager = DownloadManager.Builder(mActivity).run {
                            apkUrl(it.url)
                            apkName("houji_${it.ver}.apk")
                            smallIcon(com.baozhun.mall.common.R.drawable.ic_launcher)
                            forcedUpgrade(it.is_force == AppUpdateType.FORCE_UPDATE.type)
                            build()
                        }
                        manager?.download()
                    }).title(it.title).content(it.message).showCancelBt(it.is_force != AppUpdateType.FORCE_UPDATE.type).clickNotDismiss()).show()
            }
        }
    }

    override fun onClick(v: View?) {
        super.onClick(v)
        when (v?.id) {
            R.id.tv_search -> {
                SearchActivity.start(mActivity)
            }

            R.id.iv_category -> { //分類
                ARouter.getInstance().build(RoutePath.Home.ALL_CATEGORY).withString(Constants.Common.BUNDLE_NAME, GoodsType.CHANNEL.type).navigation()
            }
        }
    }

    private fun initCategoryNavData(homePageBean: HomePageBean) {
        homePageBean.category_bar?.let {
            mFragmentList.clear()
            mViewModel.categoryList.clear()
            mViewModel.categoryList.addAll(it)
        }
        for (category in mViewModel.categoryList) {
            val fragment = CategoryFragment.newInstance(category.id, true, category.sub, mViewModel.categoryList.indexOf(category) == 0)
            mFragmentList.add(fragment)
        }
        mCategoryPageListAdapter = CategoryPageListAdapter(this, mFragmentList)
        mDataBinding.homeCategoryViewpager.adapter = mCategoryPageListAdapter
        TabLayoutMediator(mDataBinding.homeCategoryTabLayout, mDataBinding.homeCategoryViewpager.viewPager2) { tab, position ->
            tab.text = mViewModel.categoryList[position].navi_name
        }?.attach()
        mDataBinding.homeCategoryViewpager.offscreenPageLimit = 1
        mDataBinding.homeCategoryViewpager.currentItem = 0
        mDataBinding.homeCategoryTabLayout.removeOnTabSelectedListener(this)
        mDataBinding.homeCategoryTabLayout.addOnTabSelectedListener(this)
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        lazyLoadData()
    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {
        if (mFragmentList.isEmpty()) return
        mFragmentList[mDataBinding.homeCategoryViewpager.currentItem].onLoadMore(refreshLayout)
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: EventMessage<Any>) {
        if (event.eventCode == EventCode.LOGIN_SUCCESS) {
            //登陆成功刷新首页余额兑换专区数据
            lazyLoadData()
        } else if (event.eventCode == EventCode.LOG_OUT) {
            //退出登陆成功刷新首页余额兑换专区数据
            lazyLoadData()
            mViewModel.isReadPointUseTerms.value = false
        }
    }

    /**
     * 初始化顶金刚位
     */
    private fun initTopCategoryClass(categoryData: ArrayList<HomeGoldenBean>) {
        if (categoryData.isNullOrEmpty()) {
            mDataBinding.llCategory.visibility = GONE
            return
        } else {
            mDataBinding.llCategory.visibility = VISIBLE
        }
        mDataBinding.vpCategory.setAdapter(HomeTopCategoryViewPagerAdapter {
            if (it.jump_type == 2) { //分类页
                if (it.category_id == 0) { //category_id为0则表示全部分类页
                    ARouter.getInstance().build(RoutePath.Home.ALL_CATEGORY).withString(Constants.Common.BUNDLE_NAME, GoodsType.CHANNEL.type)
                        .navigation()
                } else {
                    var classifyInfo = ClassifyInfo(it.resource_id, it.resource_name, it.resource_img, "", "", "", arrayListOf()).apply {
                        goods_type = GoodsType.CHANNEL.type
                    }
                    ARouter.getInstance().build(RoutePath.Home.CATEGORY_GOODS_LIST)
                        .withSerializable(Constants.Common.BUNDLE_NAME, classifyInfo)
                        .navigation()
                }
            } else if (it.jump_type == 6) { //外部链接
                WebContainerActivity.start(mActivity, it.jump_url, it.resource_name)
            }
        })
        var classData = AppUtil.transformClassData(categoryData, 10)
        mCategoryViewPageSize = if (classData?.size == 0) 1 else classData?.size!!
        mDataBinding.vpCategory.create(classData)
        mDataBinding.vpCategory.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {

            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                var position = if (position == mCategoryViewPageSize - 1) mCategoryViewPageSize else position
                mDataBinding.categoryIndicator.setProgress(position.toFloat() / mCategoryViewPageSize)
            }
        })

        mViewModel.mShowCategoryIndicator.value = classData.size > 1
        mDataBinding.categoryIndicator.setTotalCount(mCategoryViewPageSize)
    }

    override fun onStickyChange(oldStickyView: View?, newStickyView: View?) {
        if (oldStickyView == null) { //已吸顶
//            mViewModel.isSticky.postValue(true)
//            StatusBarUtil.setLightMode(requireActivity())
        } else {
//            mViewModel.isSticky.postValue(false)
//            StatusBarUtil.setDarkMode(requireActivity())
        }
    }

    override fun onScrollChange(v: View?, scrollY: Int, oldScrollY: Int, scrollState: Int) {
        try {
//            var layoutManager = mFragmentList[mDataBinding.homeCategoryViewpager.currentItem].mDataBinding.categoryRecycleView.layoutManager
//            if (layoutManager is StaggeredGridLayoutManager) {
//                var lastVisibleItemArray = IntArray(layoutManager.spanCount)
//                layoutManager.findLastCompletelyVisibleItemPositions(lastVisibleItemArray)
//                Logger.e("onScrollChange-lastVisibleItemArray->${lastVisibleItemArray[0]}")
//                Logger.e("onScrollChange-getItemCount->${layoutManager.getItemCount()}")
//                Logger.e("onScrollChange-autoLoadMore->${lastVisibleItemArray[0] == layoutManager.getItemCount() - 1 - Constants.Common.PRELOAD_COUNT}")
//                if (lastVisibleItemArray[0] == layoutManager.getItemCount() - 1 - Constants.Common.PRELOAD_COUNT) {
//                    if (!mDataBinding.homeRefreshRv.isLoading) {
//                        Logger.e("onScrollChange-->autoLoadMore")
//                        mDataBinding.homeRefreshRv.autoLoadMore()
//                    }
//                }
//            }
        } catch (e: Exception) {
            Logger.e(e.toString())
        }

//        if (mViewModel.isSticky.value != true) {
//            var stickViewY = mDataBinding.rlStickView.y
//            var ratio = scrollY / stickViewY
//            mDataBinding.clSearch.alpha = 1f - ratio
//        } else {
//            mDataBinding.clSearch.alpha = 1f
//        }

    }

    override fun onTabSelected(tab: TabLayout.Tab?) {
        Logger.e("onTabSelected===>${tab?.text.toString()}")
        //分类自动滑动到顶部
//        if (mIsInit) { //首次加载不作处理
//            mIsInit = false
//        } else {
//            mDataBinding.scrollerLayout.scrollToChild(mDataBinding.rlStickView)
//        }
//                mDataBinding.clSearch.alpha = 1f
    }

    override fun onTabUnselected(tab: TabLayout.Tab?) {
    }

    override fun onTabReselected(tab: TabLayout.Tab?) {
    }


    override fun onLongClick(v: View?): Boolean {
        if (BuildConfig.BUILD_TYPE == "release") return true
        XPopup.Builder(context).asBottomList("请选择接口环境", ApiEnvironment.values().map { it.desc }.toTypedArray()) { i: Int, s: String ->
            SPUtils.getInstance().put(Constants.Common.API_TYPE, i)
            CacheUtil.clearUserInfo()
            showToast(com.baozhun.mall.res.R.string.service_change_success_hint)
        }.show()
        return true
    }

}